package com.dyp.argumentvalidation.ctr;

import com.dyp.argumentvalidation.model.ErrorResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice  // 可以省掉方法上的@ResponseBody注解
//@ControllerAdvice
public class GlobalExceptionHandler {
    //全局异常处理，可以有多个ExceptionHandler
    /**
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(value= HttpStatus.BAD_REQUEST)
//    @ResponseBody
    public ErrorResponse handleAnyException(MethodArgumentNotValidException ex, HttpServletRequest request,
                                            HttpServletResponse response) {
        ErrorResponse error = new ErrorResponse(request.getRequestURI(), request.getMethod(),
                HttpStatus.BAD_REQUEST.value(), ex.getMessage() +"excepton class: " +ex.getClass()
                , null != ex.getCause() ? ex.getCause().getMessage():"");

        ex.printStackTrace();
        return error;
    }
    // ctr层 valid异常抛出捕获
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(value= HttpStatus.BAD_REQUEST)
//    @ResponseBody
    public ErrorResponse handleConstraintViolationException(ConstraintViolationException ex, HttpServletRequest request,
                                                            HttpServletResponse response) {
        ErrorResponse error = new ErrorResponse(request.getRequestURI(), request.getMethod(),
                HttpStatus.BAD_REQUEST.value(), ex.getMessage() +"excepton class: " +ex.getClass()
                , null != ex.getCause() ? ex.getCause().getMessage():"");

        ex.printStackTrace();
        return error;
    }


    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value= HttpStatus.BAD_REQUEST)
    //    @ResponseBody
    public ErrorResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException ex, HttpServletRequest request,
                                                            HttpServletResponse response) {
        ErrorResponse error = new ErrorResponse(request.getRequestURI(), request.getMethod(),
                HttpStatus.BAD_REQUEST.value(), ex.getMessage() +"excepton class: " +ex.getClass()
                , null != ex.getCause() ? ex.getCause().getMessage():"");

        ex.printStackTrace();
        return error;
    }
}
